import { Modal } from 'ant-design-vue'
import { onActivated, onDeactivated, onMounted, onUnmounted, ref } from 'vue'
import { isDevOrDevelopment } from '@/shared/env'
import { useLocalStorage } from '@vueuse/core'
import { StorageEnum } from '@/core/enums/shared'

export function useReloadModal() {
  const timer = ref<any>()

  function timerFn() {
    // 6小时
    const time = 1000 * 60 * 60 * 6
    const storageTime = useLocalStorage(StorageEnum.ReloadTime, null)

    return setTimeout(
      () => {
        Modal.confirm({
          title: '温馨提示',
          content: '您在此页面停留时间过长，部分数据已发生变化，请点击确定刷新页面继续使用。',
          onOk() {
            window.location.reload()
          },
          cancelButtonProps: {
            disabled: true
          }
        })
      },
      isDevOrDevelopment ? storageTime.value || time : time
    )
  }

  onMounted(() => {
    if (!timer.value) {
      timer.value = timerFn()
    }
  })

  onActivated(() => {
    if (!timer.value) {
      timer.value = timerFn()
    }
  })

  onUnmounted(() => {
    clearTimeout(timer.value)
    timer.value = undefined
  })

  onDeactivated(() => {
    clearTimeout(timer.value)
    timer.value = undefined
  })
}
